package com.yang.filter;

import com.alibaba.fastjson.JSON;
import com.yang.domain.Result;
import com.yang.domain.entity.LoginUser;
import com.yang.enums.AppHttpCodeEnum;
import com.yang.utils.JwtUtil;
import com.yang.utils.RedisCache;
import com.yang.utils.WebUtils;
import io.jsonwebtoken.Claims;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import static com.yang.constants.RedisConstants.BLOG_LOGIN;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Resource
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //1.获取请求头中的token
        String token = request.getHeader("token");

        //2.token为空，说明这个页面是不需要拦截的
        if (!StringUtils.hasText(token)){
            //直接放行，交给后面的拦截器校验
            filterChain.doFilter(request,response);
            return;
        }

        //3.不为空，从token里面解析出userId
        Claims claims;
        try {
            claims = JwtUtil.parseJWT(token);
        } catch (Exception e) {
            e.printStackTrace();
            //token超时，说明这个token过期了,告诉前端需要重新登录
            Result result = Result.errorResult(AppHttpCodeEnum.NEED_LOGIN);
            WebUtils.renderString(response, JSON.toJSONString(result));
            return;
        }
        String userId = claims.getSubject();

        //4.从redis获取用户
        LoginUser loginUser = redisCache.getCacheObject(BLOG_LOGIN + userId);

        //5.判断用户是否过期
        if (Objects.isNull(loginUser)){
            //redis缓存的数据过期 提示从新登陆
            Result result = Result.errorResult(AppHttpCodeEnum.NEED_LOGIN);
            WebUtils.renderString(response, JSON.toJSONString(result));
            return;
        }

        //6.没过期，并且刷新当前登录用户的过期时间
        redisCache.expire(BLOG_LOGIN + userId,60, TimeUnit.MINUTES);

        //7.存入到 SecurityContextHolder 当中
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser,null,null);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        //8.放行
        filterChain.doFilter(request,response);
    }
}


